package com.ly.spring.mvc.web;




import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConvertor implements Converter<String, Date> {

    SimpleDateFormat yyyymmdd1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat yyyymmdd2 = new SimpleDateFormat("yyyy年MM月dd日");
    SimpleDateFormat yyyymmddhhmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat yyyymmddhhmmss2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");


    @Override
    public Date convert(String source) {
        if (source == null || source.isBlank())return null;
            source = source.trim();
            if (source.length() == "yyyy-MM-dd".length()){
                return parse(yyyymmdd1,source);
            }else if (source.length() == "yyyy年MM月dd日".length()){
                return parse(yyyymmdd2,source);
            }else if (source.length() == "yyyy-MM-dd HH:mm:ss".length()){
                return parse(yyyymmddhhmmss,source);
            }else if (source.length() == "yyyy年MM月dd日 HH时mm分ss秒".length()){
                return parse(yyyymmddhhmmss2,source);
            }
            return null;
    }

    private Date parse(SimpleDateFormat fmt,String source) {
        try {
            return fmt.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

}
